<template>
  <!-- 人员能力表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="700"
    draggable
    @close="closeDialog"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请输入工厂"
              clearable
              style="width: 230px"
              @change="changePlant"
              filterable
            >
              <el-option
                v-for="plant in plantList"
                :key="plant.id"
                :label="plant.organizationCode"
                :value="plant.id"
              />
            </el-select>
            <span v-else>{{ plantCode(formData.plantId) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作中心" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.workCenterId"
              placeholder="请输入工作中心"
              clearable
              style="width: 230px"
              :disabled="formData.plantId === ''"
              @change="changeWorkCenter"
              filterable
            >
              <el-option
                v-for="item in workCenters"
                :key="item.id"
                :label="`${item.workshopCode}-${item.workshopName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.workCenterCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工序" prop="processId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.processId"
              placeholder="请输入工序"
              clearable
              style="width: 230px"
              :disabled="formData.workCenterId === ''"
              @change="changeProcess"
              filterable
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="`${item.processCode}-${item.processName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.processCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="技能熟练度" prop="skillProficiency">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.skillProficiency"
              placeholder="请选择物料类型"
              clearable
              style="width: 230px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('SkillLevel')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("SkillLevel", formData.skillProficiency)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="班组" prop="crewId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.crewId"
              placeholder="请输入班组"
              clearable
              style="width: 230px"
              :disabled="formData.workCenterId === ''"
              @change="changeCrew"
              filterable
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="`${item.crewCode}-${item.crewName}`"
                :value="item.id"
              />
            </el-select>

            <span v-else>{{ formData.crewName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成员姓名" prop="memberId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.memberId"
              placeholder="请输入成员"
              clearable
              style="width: 230px"
              :disabled="formData.crewId === ''"
              @change="changeMember"
              filterable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="`${item.memberEmpNo}-${item.memberName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{
              `${formData.memberEmpNo}-${formData.memberName}`
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="是否启用" prop="enabled">
        <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
        <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-if="!props.isReadonly"
          v-model="formData.remarks"
          placeholder="请输入备注"
          clearable
          type="textarea"
        />

        <text v-else>{{ formData.remarks }}</text>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="创建时间"
            prop="createTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createTime"
              disabled
            />

            <span v-else>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="创建人"
            prop="createdUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserName"
              disabled
            />

            <span v-else>{{ formData.createdUserName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新时间"
            prop="lastUpdateTime"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              disabled
            />

            <span v-else>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="更新人"
            prop="lastUpdatedUserName"
            v-if="props.isReadonly"
          >
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserName"
              disabled
            />

            <span v-else>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESMEMBERABILITYADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  crewId: [{ required: true, message: "请选择班组", trigger: "change" }],
  memberId: [{ required: true, message: "请选择人员", trigger: "change" }],
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  workCenterId: [
    { required: true, message: "请选择工作中心", trigger: "change" },
  ],
  processId: [{ required: true, message: "请选择工序", trigger: "change" }],
  skillProficiency: [
    { required: true, message: "请选择技能熟练程度", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});
const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  memberId: "",
  memberEmpNo: "",
  memberName: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  processId: "",
  processCode: "",
  processName: "",
  crewId: "",
  crewCode: "",
  crewName: "",
  skillProficiency: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    //新增时清除下拉列表数据
    workCenters.value = [];
    processList.value = [];
    crewList.value = [];
    memberList.value = [];
    if (newVal?.id) {
      const {
        id,
        memberId,
        memberEmpNo,
        memberName,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        processId,
        processCode,
        processName,
        crewId,
        crewCode,
        crewName,
        skillProficiency,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        memberId,
        memberEmpNo,
        memberName,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        workCenterId,
        workCenterCode,
        processId,
        processCode,
        processName,
        crewId,
        crewCode,
        crewName,
        skillProficiency,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      getWorkCenters();
      getProcess();
      getCrews();
      getMember();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.crewId = "";
  formData.crewCode = "";
  formData.crewName = "";
  formData.skillProficiency = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);

/** 人员能力保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/mesmemberability/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
onMounted(() => {
  getPlantList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
//工厂列表
const plantList = ref([]);

const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
//工厂变更时触发
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  //工厂变更清除关联内容
  formData.workCenterId = "";
  formData.workCenterCode = "";
  workCenters.value = [];
  getWorkCenters();
  formData.processId = "";
  formData.processCode = "";
  processList.value = [];
  formData.crewId = "";
  formData.crewCode = "";
  formData.crewName = "";
  crewList.value = [];
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
  memberList.value = [];
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
//工作中心
const workCenters = ref([]);
async function getWorkCenters() {
  if (formData.plantId) {
    await request({
      url: "mes/mesworkshop/getList",
      method: "post",
      data: { plantId: formData.plantId, enabled: 1 },
    }).then((res) => {
      workCenters.value = res.data;
      console.log(workCenters);
    });
  }
}
//工作中心赋值
const changeWorkCenter = (id: any) => {
  formData.workCenterId = id;
  workCenters.value.forEach((item) => {
    if (item.id === id) {
      formData.workCenterCode = item.workshopCode;
    }
  });
  formData.processId = "";
  formData.processCode = "";
  processList.value = [];
  getProcess();
  formData.crewId = "";
  formData.crewCode = "";
  formData.crewName = "";
  crewList.value = [];
  getCrews();
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
};
// 工序
const processList = ref([]);
const changeProcess = (id: any) => {
  formData.processId = id;
  processList.value.forEach((item) => {
    if (item.id === id) {
      formData.processCode = item.processCode;
    }
  });
};
async function getProcess() {
  if (formData.workCenterId) {
    await request({
      url: "mes/mesprocess/getList",
      method: "post",
      data: {
        plantId: formData.plantId,
        workCenterId: formData.workCenterId,
        enabled: 1,
      },
    }).then((res) => {
      processList.value = res.data;
    });
  }
}
//班组
const crewList = ref([]);

const changeCrew = (id: any) => {
  formData.crewId = id;
  crewList.value.forEach((item) => {
    if (item.id === id) {
      formData.crewCode = item.crewCode;
      formData.crewName = item.crewName;
    }
  });
  formData.memberId = "";
  formData.memberEmpNo = "";
  formData.memberName = "";
  getMember();
};
async function getCrews() {
  if (formData.workCenterId) {
    await request({
      url: "mes/mescrew/getCrew",
      method: "post",
      data: {
        plantId: formData.plantId,
        workCenterId: formData.workCenterId,
        enabled: 1,
      },
    }).then((res) => {
      crewList.value = res.data;
    });
  }
}
//人员
const memberList = ref([]);
const changeMember = (id: any) => {
  formData.memberId = id;
  memberList.value.forEach((item) => {
    if (item.id === id) {
      formData.memberEmpNo = item.memberEmpNo;
      formData.memberName = item.memberName;
    }
  });
};
async function getMember() {
  if (formData.workCenterId) {
    await request({
      url: "mes/mescrew/getCrewMembers",
      method: "post",
      data: {
        id: formData.crewId,
      },
    }).then((res) => {
      memberList.value = res.data;
    });
  }
}
</script>
